#pragma once
#include "Socket.hpp"
#include <sys/select.h>
#include <sys/time.h>
using namespace std;
static const uint16_t defaultport = 8080;
static const uint32_t fd_num_max = (sizeof(fd_set) * 8);
int defaultfd = -1;
class SelectServer
{
public:
    SelectServer(uint16_t port = defaultport) : _port(port)
    {
        for (int i = 0; i < fd_num_max; i++)
        {
            fd_array[i] = defaultfd;
            // cout << "fd_array[" << i << "]" << ": " << fd_array[i] << endl;
        }
    }
    bool Init()
    {
        _listensock.Socket();
        _listensock.Bind(_port);
        _listensock.Listen();
        return true;
    }
    void Accepter()
    {
        std::string clientip;
        uint16_t clientport = 0;
        int sock = _listensock.Accept(&clientip, &clientport);
        if (sock < 0)
            return;
        log(Info, "Accept Success, %s:%d, fd: %d", clientip.c_str(), clientport, sock);
        int pos = 1;
        for (; pos < fd_num_max; pos++)
        {
            if (fd_array[pos] != defaultfd)
                continue;
            else
                break;
        }
        if (pos == fd_num_max)
        {
            log(Warning, "server is full,close %d now!", sock);
            close(sock);
        }
        else
        {
            fd_array[pos] = sock;
            PrintFd();
            // todo
        }
    }
    void Recver(int fd, int pos)
    {
        // demo读取
        char buffer[1024];
        size_t n = read(fd, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n] = 0;
            cout << "Get a message: " << buffer << endl;
        }
        else if (n == 0) // 对方将读fd关闭
        {
            log(Info, "client quit,me too,close fd is: ", fd);
            close(fd);
            fd_array[pos] = defaultfd; // 从select中移除
        }
        else
        {
            log(Warning, "recv error,close fd is: ", fd);
            close(fd);
            fd_array[pos] = defaultfd; // 从select中移除
        }
    }
    void Dispatcher(fd_set &rfds) // 事件派发器
    {
        for (int i = 0; i < fd_num_max; i++)
        {
            int fd = fd_array[i];
            if (fd == defaultfd)
                continue;
            if (FD_ISSET(fd, &rfds))
            {
                // 链接事件,获取新链接
                if (fd == _listensock.Fd())
                {
                    Accepter(); // 链接管理器
                }
                else // 非listensock
                {
                    Recver(fd, i);
                }
            }
        }
    }
    void Start()
    {
        int listensock = _listensock.Fd();
        fd_array[0] = listensock;
        while (true)
        {
            fd_set rfds;
            FD_ZERO(&rfds);
            int maxfd = fd_array[0];
            for (int i = 0; i < fd_num_max; i++)
            {
                if (fd_array[i] == defaultfd)
                    continue;
                FD_SET(fd_array[i], &rfds);
                if (maxfd < fd_array[i])
                {
                    maxfd = fd_array[i];
                    log(Info, "max fd update,maxfd is %d", maxfd);
                }
            }
            // struct timeval timeout = {1, 0}; // 对输入输出型参数进行操作时，可能需要重复周期性地设置
            struct timeval timeout = {0, 0}; // 设置为0则是非阻塞式
            // 若timeout未设置则永久阻塞，直到事件到来
            int n = select(maxfd + 1, &rfds, nullptr, nullptr, /*&timeout*/ nullptr);
            switch (n)
            {
            case 0:
                cout << "time out,timeout: " << timeout.tv_sec << "." << timeout.tv_usec << endl;
                break;
            case -1:
                cerr << "select error" << endl;
                break;
            default:
                // 有事件已经就绪
                // 上层如果不及时将事件取走，否则select一直通知你
                cout << "get a new link" << endl;
                Dispatcher(rfds);
                break;
            }
        }
    }
    void PrintFd()
    {
        cout << "online fd list: ";
        for (int i = 0; i < fd_num_max; i++)
        {
            if (fd_array[i] == defaultfd)
                continue;
            cout << fd_array[i] << " ";
        }
        cout << endl;
    }
    ~SelectServer()
    {
        _listensock.Close();
    }

private:
    MySocket _listensock;
    uint16_t _port;
    int fd_array[fd_num_max];
};